/**
 * Copyright 2004 - 2007 Blue Bamboo International Inc. 
 *           All rights reserved.
 *
 *
 * Blue Bamboo PROPRIETARY/CONFIDENTIAL.
 *
 */

package com.bambamboo.socket.server.mina;

import java.net.InetSocketAddress;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.mina.transport.socket.SocketAcceptor;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

import com.bambamboo.socket.server.AbstractIOServer;
import com.bambamboo.socket.server.ServerConfigurationBean;

/**
 * DOCME
 * 
 * @author Nick.Tan
 */
public class MinaTCPServer extends AbstractIOServer {

	private static Log logger = LogFactory.getLog(MinaTCPServer.class);

	@Override
	public void startup() throws Exception {
		SocketAcceptor acceptor = new NioSocketAcceptor();
		ServerConfigurationBean bean = getServerConfigurationBean();
		BaseIoHandler iohandler = null;
		String handlerClassname = bean.getHandler();
		if (handlerClassname == null || handlerClassname.trim().length() == 0) {
			iohandler = new DefaultIoHandler();
		}
		else {
			Class ioHandlerClazz = Class.forName(bean.getHandler());
			iohandler = (BaseIoHandler) ioHandlerClazz.newInstance();
		}
		iohandler.setConfigurationBean(bean);
		acceptor.setHandler(iohandler);
		String port = bean.getPort();
		try {
			acceptor.bind(new InetSocketAddress(Integer.parseInt(port)));
			logger.info(String.format(">>> listening on port [%s]", port));
		}
		catch (Exception e) {
			// catch to continue binding other ports
			logger.error(String.format(">>> binding on port [%s] failure!", port), e);
		}
	}

}
